<template>
  <div>
    <el-card>
      <el-form label-width="120px" :model="dataForm" :rules="dataRules" ref="dataDom">
        <el-form-item label="spu名称" size="mini">
          <span>{{ spuName }}</span>
        </el-form-item>
        <el-form-item label="skuName" size="mini" prop="skuName">
          <el-input size="mini" v-model="dataForm.skuName" />
        </el-form-item>
        <el-form-item label="价格(元)" size="mini" prop="price">
          <el-input type="number" size="mini" min="1" v-model="dataForm.price" />
        </el-form-item>
        <el-form-item label="重量(千克)" size="mini" prop="weight">
          <el-input type="number" min="1" size="mini" v-model="dataForm.weight" />
        </el-form-item>
        <el-form-item label="规格描述" size="mini" prop="skuDesc">
          <el-input type="textarea" size="mini" row="3" v-model="dataForm.skuDesc" />
        </el-form-item>
        <el-form-item label="平台属性" prop="skuAttrValueList">
          <el-row class="row">
            <el-col
              v-for="(item, index) in attrInfoList"
              :key="item.id"
              class="el-coll"
              :xs="24"
              :md="12"
              :lg="8"
              :xl="6"
              ><div class="grid-content bg-purple">
                <el-form-item size="mini" :label="item.attrName" class="item">
                  <el-select
                    v-model="dataForm.skuAttrValueList[index]"
                    @change="reValidate('skuAttrValueList')"
                  >
                    <el-option
                      :value="item.id + ':' + item.attrName + ':' + obj.id + ':' + obj.valueName"
                      :label="obj.valueName"
                      v-for="(obj, index) in item.attrValueList"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item></div
            ></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="销售属性" prop="skuSaleAttrValueList">
          <el-row class="row">
            <el-col
              v-for="(item, index) in saleAttrList"
              :key="item.id"
              class="el-coll"
              :xs="24"
              :md="12"
              :lg="8"
              :xl="6"
              ><div class="grid-content bg-purple">
                <el-form-item size="mini" :label="item.saleAttrName" class="item">
                  <el-select
                    v-model="dataForm.skuSaleAttrValueList[index]"
                    @change="reValidate('skuSaleAttrValueList')"
                  >
                    <el-option
                      :value="`${item.id}:${item.saleAttrName}:${obj.id}:${obj.saleAttrValueName}`"
                      :label="obj.saleAttrValueName"
                      v-for="(obj, index) in item.spuSaleAttrValueList"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item></div
            ></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="图片列表" prop="skuImageList">
          <el-table
            :data="skuImageList11"
            style="width: 100%"
            border
            @select="selectImg"
            @select-all="selectall"
          >
            <el-table-column prop="date" label="日期" width="80" type="selection">
            </el-table-column>
            <el-table-column prop="imgUrl" label="图片">
              <template v-slot="{ row }">
                <img :src="row.imgUrl" alt="" width="100" height="100" />
              </template>
            </el-table-column>
            <el-table-column prop="imgName" label="名称"> </el-table-column>
            <el-table-column prop="address" label="操作">
              <template v-slot="{ row }">
                <div class="wrap">
                  <el-tag class="tag" v-show="row.isDefault == '1'" type="success" size="mini">
                    默认</el-tag
                  >
                  <el-button
                    class="button"
                    v-show="row.isDefault == '0'"
                    type="primary"
                    size="mini"
                    @click="setDeafult(row)"
                    >设置默认</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-form-item>
            <el-button size="small" type="primary" @click="saveSku">保存</el-button>
            <el-button size="small" @click="$emit('toggle', 0)">取消</el-button>
          </el-form-item>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
export default {
  name: 'AddSku',
  data() {
    const spuName = this.$store.state.spu.spuName
    return {
      select: '',
      spuName,
      skuImageList11: [],
      dataForm: {
        isSale: 0,
        price: null,
        skuDefaultImg: '',
        skuDesc: '',
        weight: '',
        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: 'string',
          //   id: 0,
          //   skuId: 0,
          //   valueId: 0,
          //   valueName: 'string'
          // }
        ],

        skuImageList: [
          // {
          //   id: 0,
          //   imgName: 'string',
          //   imgUrl: 'string',
          //   isDefault: 'string',
          //   skuId: 0,
          //   spuImgId: 0
          // }
        ],
        skuName: '',
        skuSaleAttrValueList: [
          // {
          //   id: 0,
          //   saleAttrId: 0,
          //   saleAttrName: 'string',
          //   saleAttrValueId: 0,
          //   saleAttrValueName: 'string',
          //   skuId: 0,
          //   spuId: 0
          // }
        ]
      },
      dataRules: {
        skuName: {
          required: true,
          message: '请输入spu名称',
          trigger: 'blur'
        },
        price: {
          required: true,
          message: '请输入spu名称',
          trigger: 'blur'
        },
        weight: {
          required: true,
          message: '请输入spu名称',
          trigger: 'blur'
        },
        skuDesc: {
          required: true,
          message: '请输入spu名称',
          trigger: 'blur'
        },
        skuAttrValueList: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value.length) {
              callback(new Error('请至少选择一个平台属性'))
              return
            }
            // 每个销售属性至少添加一个属性值
            // if (value.some(spuSaleAttr => !spuSaleAttr.spuSaleAttrValueList.length)) {
            //   callback(new Error('每个销售属性至少添加一个属性值'))
            //   return
            // }
            // 一定要调用，校验通过
            callback()
          }
        },
        skuSaleAttrValueList: {
          required: true,
          validator: (rule, value, callback) => {
            var arr = value.filter(value => {
              return value
            })

            if (!value.length) {
              callback(new Error('请选择销售属性'))
              return
            }
            // 每个销售属性至少添加一个属性值
            if (arr.length !== this.saleAttrList.length) {
              callback(new Error('所有销售属性都要选择哦'))
              return
            }
            // 一定要调用，校验通过
            callback()
          }
        },
        skuImageList: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value.length) {
              callback(new Error('请至少选择一张图片'))
              return
            }
            console.log(value)
            if (!value.some(item => item.isDefault === '1')) {
              callback(new Error('请选择默认图片'))
            }
            callback()
          }
        }
      }
    }
  },
  async beforeMount() {
    const { spuId } = this
    await this.getAttrInfoList()
    await this.getSaleAttrList(spuId)
    await this.getSpuImageList(spuId)
    this.skuImageList11 = this.spuImageList.map(item => {
      return { ...item, isDefault: '0' }
    })
  },
  computed: {
    ...mapState({
      attrInfoList: state => state.attr.attrInfoList,
      spuId: state => state.spu.spuId,
      spuImageList: state => state.spu.spuImageList,
      saleAttrList: state => state.spu.saleAttrList
    })
  },
  methods: {
    ...mapActions('attr', ['getAttrInfoList']),
    ...mapActions('spu', ['getSaleAttrList', 'getSpuImageList']),
    ...mapActions('sku', ['addReqSaveSpuList']),
    //点击选择框触发的函数
    selectImg(selection, row) {
      this.dataForm.skuImageList = selection
      this.reValidate('skuImageList')
    },
    selectall(selection) {
      this.dataForm.skuImageList = selection
      this.reValidate('skuImageList')
    },
    //设置默认图片
    setDeafult(row) {
      this.dataForm.skuDefaultImg = row.imgUrl
      this.skuImageList11.forEach(item => {
        if (item.id == row.id) {
          row.isDefault = '1'
        } else {
          item.isDefault = '0'
        }
      })
      // this.dataForm.skuImageList = this.skuImageList11
      this.reValidate('skuImageList')
    },
    async saveSku() {
      try {
        await this.$refs.dataDom.validate()
        var skuAttrValueList = this.dataForm.skuAttrValueList.map(text => {
          const [attrId, attrName, valueId, valueName] = text.split(':')
          return { attrId, attrName, valueId, valueName }
        })
        var skuSaleAttrValueList = this.dataForm.skuSaleAttrValueList.map(text => {
          const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = text.split(':')
          return { saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName }
        })
        var obj = { ...this.dataForm, skuAttrValueList, skuSaleAttrValueList }
        console.log(obj)
        await this.addReqSaveSpuList(obj)
        this.$message.success('添加sku成功!!')
        this.$emit('toggle', 0)
        // console.log(this.dataForm)
      } catch (error) {}
    },
    async reValidate(key) {
      try {
        await this.$refs.dataDom.validateField(key)
      } catch (error) {}
    }
  }
}
</script>

<style lang="scss" scoped>
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  // background: #99a9bf;
}
.bg-purple {
  // background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row {
  width: 100%;
}
.el-coll {
  margin-bottom: 10px;
}
.item {
  transform: translateX(-70px);
}
.wrap {
  width: 100%;
  height: 100px;
  // background-color: red;
  position: relative;
}
.tag {
  position: absolute;
  left: 0;
  top: 35px;
}
.button {
  position: absolute;
  width: 80px;
  left: 0;
  top: 35px;
}
</style>
